package techniques.opencv;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

public class OpenCVChangeDetection {
	
	public static void main(String[] args) {
		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
		String local = "C:/images/A/";
	    String simg1 = "image_diff2.jpg";

		Mat origem = Highgui.imread(local + simg1,
				Highgui.CV_LOAD_IMAGE_COLOR);

		Mat threeChannel = new Mat();
        Imgproc.cvtColor(origem, threeChannel, Imgproc.COLOR_BGR2GRAY);
        Imgproc.threshold(threeChannel, threeChannel, 150, 255, Imgproc.THRESH_BINARY);
        
        Highgui.imwrite(local + "image_diffThreeChannel.jpg", threeChannel);
        
        Mat fg = new Mat(origem.size(),CvType.CV_8U);
        Imgproc.erode(threeChannel,fg,new Mat(),new Point(-1,-1),2);
        Highgui.imwrite(local + "image_fg.jpg", fg);

        Mat bg = new Mat(origem.size(),CvType.CV_8U);
        Imgproc.dilate(threeChannel,bg,new Mat(),new Point(-1,-1),3);
        Imgproc.threshold(bg,bg,1, 128,Imgproc.THRESH_BINARY_INV);
        Highgui.imwrite(local + "image_bg.jpg", bg);

        Mat markers = new Mat(origem.size(),CvType.CV_8U, new Scalar(0));
        Core.add(fg, bg, markers);
        Highgui.imwrite(local + "image_markes.jpg", markers);

        WatershedSegmenter segmenter = new WatershedSegmenter();
        segmenter.setMarkers(markers);
        Mat result = segmenter.process(origem);
        Highgui.imwrite(local + "Seg.jpg", result);
	}

}

class WatershedSegmenter{
    public Mat markers;

    public void setMarkers(Mat markerImage)
    {
    	markers = markerImage;
        markerImage.convertTo(markers, CvType.CV_32S);
    }

    public Mat process(Mat image)
    {
        Imgproc.watershed(image, markers);
       // markers.convertTo(markers,CvType.CV_8U);
        return markers;
    }
}
